package admin

import (
	"booking/common/handler"
	"booking/common/validator"
	"booking/models"

	"github.com/gin-gonic/gin"
)

func List(c *gin.Context) {
	var params struct {
		models.PageInfo
		Username string `json:"username,omitempty"`
		Nickname string `json:"nickname,omitempty"`
		Mobile   string `json:"mobile,omitempty"`
		Status   *int   `json:"status"`
	}

	if err := c.ShouldBindJSON(&params); err != nil {
		handler.Error(validator.Translate(err), c)
		return
	}

	var adminList []models.Admin
	var total int64
	query := models.Db.
		Model(models.Admin{}).Where("id <> ?", 1)

	if params.Username != "" {
		query.Where("username LIKE ?", "%"+params.Username+"%")
	}
	if params.Nickname != "" {
		query.Where("nickname LIKE ?", "%"+params.Nickname+"%")
	}
	if params.Mobile != "" {
		query.Where("mobile LIKE ?", "%"+params.Mobile+"%")
	}
	if params.Status != nil {
		query.Where(map[string]interface{}{"status": *params.Status})
	}

	query.Count(&total)
	var data = handler.Data{
		TotalCount: total,
		PageIndex:  params.DefPage(),
		PageSize:   params.DefPageSize(),
	}
	query.Offset(params.Offset()).
		Limit(params.DefPageSize()).
		Order("id desc").
		Find(&adminList)

	var list = make([]map[string]any, 0)
	for _, v := range adminList {
		list = append(list, map[string]any{
			"id":           v.Id,
			"username":     v.Username,
			"nickname":     v.Nickname,
			"mobile":       v.Mobile,
			"status":       v.Status,
			"status_label": models.StatusLabel[v.Status],
			"updated_time": v.UpdatedTime.Format("2006-01-02 15:04:05"),
		})
	}
	data.List = list
	data.Format()
	handler.Success(data, c)
}
